# GT-LMS Learning Management System Main Program Entry

"""
GT-LMS Learning Management System
This is a Python-based object-oriented learning management system
"""

import sys
import os

# Add project root directory to Python path
project_root = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_root)

# 导入系统模块
from system.lms_system import LMSSystem
from ui.cli import CLI

# Try to import GUI module (optional)
try:
    from ui.gui import GUI
    GUI_AVAILABLE = True
except ImportError:
    GUI_AVAILABLE = False
    print("GUI module not available, will use command line interface")

def show_help():
    """Show help information"""
    help_text = """
GT-LMS Learning Management System

Usage:
  python main.py [options]

Options:
  --gui          Launch graphical user interface (if available)
  --help, -h     Show this help information

Examples:
  python main.py          Start command line interface
  python main.py --gui    Start GUI interface
    """
    print(help_text)

def run_demo():
    """Run system demo"""
    try:
        # Create system instance
        lms_system = LMSSystem()

        # Initialize system
        if not lms_system.initialize():
            print("System initialization failed")
            return 1

        # Create test data
        print("Creating demo data...")
        if lms_system.create_test_data():
            print("Demo data created successfully")
        else:
            print("Demo data creation failed")
            return 1

        # Save data
        print("Saving demo data...")
        if lms_system.save_data():
            print("Demo data saved successfully")
        else:
            print("Demo data save failed")
            return 1

        # Display system statistics
        print("\nSystem statistics:")
        stats = lms_system.get_statistics()
        for key, value in stats.items():
            if key != "error":
                print(f"  {key}: {value}")

        print("\nDemo completed! System is ready for use.")
        print("Run 'python main.py' to start the system.")

        return 0
    except Exception as e:
        print(f"Error occurred during demo: {e}")
        return 1

def main():
    """
    Main function - program entry point
    """
    # Check command line arguments
    if len(sys.argv) > 1:
        arg = sys.argv[1].lower()
        if arg in ['--help', '-h']:
            show_help()
            return 0
        elif arg == '--demo':
            return run_demo()

    try:
        # Create LMS system instance
        lms_system = LMSSystem()

        # Initialize system
        if not lms_system.initialize():
            print("System initialization failed")
            return 1

        # Check command line arguments to determine which interface to use
        use_gui = False
        if len(sys.argv) > 1 and sys.argv[1].lower() == '--gui':
            if GUI_AVAILABLE:
                use_gui = True
            else:
                print("GUI not available, using command line interface")

        if use_gui:
            # Create and start GUI interface
            print("Starting GT-LMS Learning Management System (GUI)...")
            gui = GUI(lms_system)
            result = gui.start()
            if not result:
                print("GUI startup failed, falling back to command line interface")
                # Fall back to CLI
                cli = CLI(lms_system)
                cli.start()
        else:
            # Create command line interface
            cli = CLI(lms_system)

            # Start system
            print("Starting GT-LMS Learning Management System (CLI)...")
            cli.start()

        # System normal exit
        lms_system.shutdown()
        return 0

    except Exception as e:
        # Handle uncaught exceptions
        print(f"Error occurred during program execution: {e}")
        return 1

if __name__ == "__main__":
    # Program entry point
    exit_code = main()
    exit(exit_code)
